﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.IO;
using System.Data.SqlClient;

namespace Tsol.SandboxWebserviceSample.SandboxWebserviceSamplePart
{
    [ToolboxItemAttribute(false)]
    public class SandboxWebServicePart<T, Y> : System.Web.UI.WebControls.WebParts.WebPart
    {
        public T Response;
        public Y Request;

        protected override void OnLoad(EventArgs e)
        {
            if (!this.DesignMode && Context.Request.QueryString["parameters"] != null)
            {
                Request = (Y)JsonConvert.DeserializeObject(Context.Request.QueryString["parameters"], typeof(Y));
            }
            base.OnLoad(e);
        }

        protected virtual void Execute()
        {
        }


        public override void RenderControl(HtmlTextWriter writer)
        {
            if (!this.DesignMode && Context.Request.QueryString["parameters"] != null)
            {
                Execute();

                XmlDocument _responseDocument = new XmlDocument();
                XmlElement _responsePartElement = _responseDocument.CreateElement(this.ID);
                XmlCDataSection cDataSection = _responseDocument.CreateCDataSection(JsonConvert.SerializeObject(Response));
                _responsePartElement.AppendChild(cDataSection);

                writer.Write(_responsePartElement.OuterXml);
            }
            else
            {
                base.RenderControl(writer);
            }
        }
    }
}
